package com.xxxx.service.impl;

import com.xxxx.dao.UserMapper;
import com.xxxx.exception.PasswordIsErrorException;
import com.xxxx.exception.UserNotExistException;
import com.xxxx.exception.UsernameConflictException;
import com.xxxx.pojo.User;
import com.xxxx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author Lionel
 * @Date 2021/3/7 23:11
 * Created by IntelliJ IDEA 2020.1.
 * Project: house
 * Description：用户操作Service实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User insert(User user) throws UsernameConflictException {
        User result = userMapper.selectUserByUsername(user.getUsername());
        if (result == null) {
            userMapper.insert(user);
            System.out.println("注册的账户：" + user.getUsername());
            if (user.getRole() == 0) {
                userMapper.insertCustomer(user);
            } else if (user.getRole() == 1) {
                userMapper.insertHouseKeeper(user);
            }
            return user;
        } else {
            throw new UsernameConflictException("注册的账户(" + user.getUsername() + ")已存在！");
        }
    }

    @Override
    public Boolean login(String username, String password) throws UserNotExistException, PasswordIsErrorException {
        Boolean isExist = false;
        User user = userMapper.selectUserByUsername(username);

        if (user == null || user.getStatus() == 0) {
            throw new UserNotExistException("登录账户（" + username + ")不存在！");
        }else if (!user.getPassword().equals(password)) {
            throw new PasswordIsErrorException("账户名或密码错误！");
        } else if (user != null && user.getPassword().equals(password)) {
            isExist = true;
        }
        return isExist;
    }

    @Override
    public int getLoginRole(String username) {
        return userMapper.selectRole(username);
    }
}
